<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sugar</title>
</head>

<body>
  <p>网页视区宽度为：<span id="innerWidth">0</span>px</p>
  <p>浏览器的宽度为：<span id="outerWidth">0</span>px</p>
  <p>显示器的宽度为：<span id="screenWidth">0</span>px</p>
  <p>目前图片宽度是：<span id="imageWidth">0</span>px</p>
  <p>为下面图片选择一个宽度值：<select id="testWidthSel">
      <option value="10vw" selected="selected">10</option>
      <option value="20vw">20</option>
      <option value="30vw">30</option>
      <option value="40vw">40</option>
    </select> vw
  </p>
  <p id="forAppendImg"></p>

</body>

</html>


<script>
  (function () {
    if (typeof window.screenX === "number") {
      var $ = function (selector) {
        return document.querySelector(selector);
      }, $$ = function (selector) {
        return document.querySelectorAll(selector);
      }

      var ele = {
        inw: $("#innerWidth"),
        ouw: $("#outerWidth"),
        scw: $("#screenWidth"),
        imw: $("#imageWidth"),
        sel: $("#testWidthSel"),
        app: $("#forAppendImg"),
        img: null
      };

      var src = "http://image.zhangxinxu.com/image/study/s/s512/mm1.jpg";

      var appendImg = function () {
        // 测试图片元素
        ele.img = document.createElement("img");
        // 图片的宽度
        ele.img.style.width = ele.sel.value;
        ele.img.src = src;

        // 载入图片元素
        ele.app.appendChild(ele.img);
      }();

      var valWidth = function () {
        // 各个宽度值
        ele.inw.innerHTML = window.innerWidth;
        ele.ouw.innerHTML = window.outerWidth;
        ele.scw.innerHTML = screen.width;

        // 图片宽度值
        imgWidth();
      };

      var imgWidth = function () {
        return (ele.imw.innerHTML = parseInt(window.getComputedStyle(ele.img).width));
      };

      var myImg = new Image();
      myImg.onload = function () {
        if (imgWidth() === this.width) {
          alert("本浏览器不支持vw, vh等单位");
          ele.sel.disabled = "disabled";
        } else {
          ele.sel.addEventListener("change", function () {
            ele.img.style.width = this.value;
            valWidth();
          });
        }
      };
      myImg.src = src;

      valWidth();
      window.addEventListener("resize", valWidth);

    } else {
      alert("本浏览器不支持vw, vh等单位");
    }
  })();


</script>